package com.example.proto3;

import com.google.protobuf.InvalidProtocolBufferException;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Map;

/**
 * @auther hewenhui
 * @see <a href="hetp://www.codingmaster.com> java </a>
 */
public class TestRead {
    public static void main(String[] args) throws IOException {
        // 读取文件并进行序列化
        Contacts contacts = Contacts.parseFrom(
                Files.newInputStream(Paths.get("src/main/java/com/example/proto3/contacts.bin")));
        // 打印通讯录
        printContacts(contacts);
        System.out.println(contacts.toString());
    }

    public static void printContacts(Contacts contacts) throws InvalidProtocolBufferException {
        int i=1;
        for (PeopleInfo peopleInfo : contacts.getContactsList()){
            System.out.println("---------联系人("+(i++)+")---------");
            System.out.println("姓名："+peopleInfo.getName());
            System.out.println("年龄："+peopleInfo.getAge());
            System.out.println("电话列表：");
            for (PeopleInfo.Phone phone:peopleInfo.getPhoneList()){
                System.out.println(phone.getNumber()+" ("+phone.getType().name()+")");
            }
            if(peopleInfo.hasData()
                    && peopleInfo.getData().is(Address.class)){
                Address address = peopleInfo.getData().unpack(Address.class);
                if (!address.getHomeAddress().isEmpty()){
                    System.out.println("家庭住址："+address.getHomeAddress());
                }
                if(!address.getUnitAddress().isEmpty()){
                    System.out.println("单位地址："+address.getUnitAddress());
                }
            }
//            if(peopleInfo.hasQq()){
//
//            } else if (peopleInfo.hasWechat()) {
//
//            }else{
//
//            }
            switch (peopleInfo.getOtherContactCase()){
                case QQ:
                    System.out.println("QQ:"+peopleInfo.getQq());
                    break;
                case WECHAT:
                    System.out.println("WeChat:"+peopleInfo.getWechat());
                    break;
                default:
                    System.out.println("无其他联系方式。");
                    break;
            }

            Map<String, String> remarkMap = peopleInfo.getRemarkMap();
            for(Map.Entry<String,String> entry: remarkMap.entrySet()){
                System.out.println("    "+entry.getKey()+": "+entry.getValue());
            }

        }
    }
}
